<?php
class cookie {

	private static $_instance = null;
	private $_key;
	private $_iv;

	/**
	 * 获取实体
	 * @method getInstance
	 * @return [type]      [description]
	 * @author NewFuture
	 */
	private static function getInstance()
	{
		if (null === self::$_instance)
		{
			self::$_instance=new self();
		}
		return self::$_instance;
	}

	/**
	 * 设置cookie
	 * @method set
	 * @param  [string] $name   [description]
	 * @param  [mixed] $value  [description]
	 * @param  string $path   [存取路径]
	 * @param  [int] $expire 有些时间
	 * @author NewFuture
	 */
	public static function set($name, $value, $path = '/', $expire = null)
	{
		$instance = self::getInstance();
		$value    = $instance->_encrypt($name, $value);
		return setcookie($name, $value, $expire, $path);
	}

	/**
	 * 获取cookie
	 * @method get
	 * @param  [type] $name [description]
	 * @return [type]       [description]
	 * @author NewFuture
	 */
	public static function get($name)
	{
		if (isset($_COOKIE[$name]))
		{
			$instance = self::getInstance();
			return $instance->_decrypt($name, $_COOKIE[$name]);
		}
	}

	/**
	 * 删除
	 * @method del
	 * @param  [type] $name [description]
	 * @return [type]       [description]
	 * @author NewFuture
	 */
	public static function del($name,$path='/')
	{
		return isset($_COOKIE[$name]) ? setcookie($name, '', time() - 86400,$path) : true;
	}

	/**
	 * 解密已经加密了的cookie
	 */
	private function _decrypt($key, $text)
	{
		$key = substr($this->_key.$key.$this->_key, 0, 32);
		$cryptText = base64_decode($text);
		$decryptText = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $cryptText, MCRYPT_MODE_ECB, $this->_iv);
		return @unserialize(trim($decryptText));
	}

	/**
	 * 加密cookie
	 */
	private function _encrypt($key, $data)
	{
		$key  = substr($this->_key.$key.$this->_key, 0, 32);
		$text = serialize($data);
		$encryptText = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $this->_iv);
		return trim(base64_encode($encryptText));
	}

	private function __construct()
	{
		$this->_key = Yaf_Registry::get('config')['cookie']['key'];
		$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
		$this->_iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
	}
}